<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="单据编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="系统自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="加工车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workshopCode">
              <a-select
                v-model="model.workshopCode"
                placeholder="请选择所属车间"
                @change="workshopChange"
                style="width: 100%"
              >
                <a-select-option v-for="item in workshopOptions" :key="item.value" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="执行日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workTime">
              <j-date placeholder="请选择执行日期" v-model="model.workTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-model-item label="班次" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shift">
              <j-dict-select-tag type="list" v-model="model.shift" dictCode="shift_type" placeholder="请选择" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="班组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="team">
              <a-input v-model="model.team" placeholder="请输入班组"></a-input>
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <div v-for="(item, index) in tslProWorkshopPlanTable.dataSource" :key="index">
      <j-vxe-table-procurement
        keep-source
        :ref="`${refKeys[1]}_${index}`"
        :loading="tslProWorkshopPlanTable.loading"
        :columns="tslProWorkshopPlanTable.columns"
        :dataSource="[item]"
        :maxHeight="300"
        :disabled="formDisabled"
        :rowNumber="false"
        :rowSelection="false"
        :clickSelectRow="false"
        class="j-table-force-nowrap1"
        @edit-closed="editClosedEvent"
      >
        <template v-slot:kettleIdSlot="{ row }">
          <a-select v-model="row.kettleId" style="width: 100%">
            <a-select-option v-for="opt in row.kettleOptions" :key="opt.value" :value="opt.value">
              {{ opt.text }}
            </a-select-option>
          </a-select>
        </template>
      </j-vxe-table-procurement>
      <j-vxe-table
        keep-source
        :ref="`${refKeys[0]}_${index}`"
        :loading="tslProWorkshopPlanScheduleTable.loading"
        style="margin-left: 100px"
        :columns="tslProWorkshopPlanScheduleTable.columns"
        :dataSource="item.tslProScheduleDetail"
        :maxHeight="300"
        :disabled="formDisabled"
        :rowNumber="true"
        :rowSelection="false"
        :clickSelectRow="true"
        :toolbar="false"
      >
        <template v-slot:packshopCodeSlot="{ row }">
          <a-select v-model="row.packshopCode" style="width: 100%">
            <a-select-option v-for="opt in packshopOptions" :key="opt.value" :value="opt.value">
              {{ opt.text }}
            </a-select-option>
          </a-select>
        </template>
      </j-vxe-table>
    </div>
    <br />
    <div class="ant-descriptions-title">附件信息</div>
    <j-upload v-if="!formDisabled" v-model="model.filePath" :returnUrl="false" @change="handleFileChange" />
    <j-vxe-table
      v-if="workshopPlanFileTable.dataSource.length > 0"
      keep-source
      :ref="refKeys[2]"
      :loading="workshopPlanFileTable.loading"
      :columns="workshopPlanFileTable.columns"
      :dataSource="workshopPlanFileTable.dataSource"
      :maxHeight="300"
      :disabled="formDisabled"
      :rowNumber="true"
      :rowSelection="!formDisabled"
      :toolbar="true"
      :toolbarConfig="{
        slots: ['prefix', 'suffix'],
        btn: [],
      }"
      @valueChange="handleFileChange"
    >
      <template v-slot:action="props">
        <a @click="handlePreviewFile(props)">预览</a>
        <a-divider type="vertical" />
        <a target="_blank" rel="noopener noreferrer" :href="handleDownloadFile(props)">下载</a>
      </template>
    </j-vxe-table>
  </a-spin>
</template>

<script>
import { getAction, getFileAccessHttpUrl } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { getDate } from '../../../utils'
import { initDictOptions } from '../../../components/dict/JDictSelectUtil'
import { postAction } from '@/api/manage'
import $file from '@/libs/globalFunction/file'
import { FilePreview } from '@/utils/tslCommon'

export default {
  name: 'TslProWorkshopPlanForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
  },
  data() {
    return {
      kettleOptions: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: { workshopCode: '', salesType: '', filePath: [] },
      confirmLoading: false,
      addDefaultRowNum: 1,
      validatorRules: {
        workTime: [{ required: true, message: '请选择执行日期!' }],
        workshopCode: [{ required: true, message: '请选择加工车间!' }],
        // shift: [{ required: true, message: '请选择班次!' }],
      },
      workshopOptions: [],
      packshopOptions: [],
      refKeys: ['tslProWorkshopPlanSchedule', 'tslProWorkshopPlanProcess', 'tslProWorkshopPlanFile'],
      tableKeys: ['tslProWorkshopPlanProcess'],
      activeKey: 'tslProWorkshopPlanProcess',
      workshopPlanFileTable: {
        loading: false,
        columns: [
          {
            title: '附件名称',
            key: 'fileName',
            type: JVXETypes.normal,
            width: '200px',
            defaultValue: '',
          },
          {
            title: '文件大小',
            key: 'fileSizeFormat',
            type: JVXETypes.normal,
            width: '200px',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
        dataSource: [],
      },
      // 车间计划安排包装子表
      tslProWorkshopPlanScheduleTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '调度单号',
            key: 'scheduleCode',
            type: JVXETypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订单编号',
            key: 'orderCode',
            type: JVXETypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '客户物料编码',
            key: 'customCode',
            type: JVXETypes.normal,
            width: '140px',
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'productCode',
            type: JVXETypes.normal,
            width: '140px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'productBatchNo',
            type: JVXETypes.normal,
            width: 300,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'materialSpec',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '主计量单位',
            key: 'meUnit',
            dataIndex: 'meUnit',
            dictCode: 'ji_unit',
            type: JVXETypes.select,
            width: 100,
            disabled: true,
          },
          {
            title: '计划数量',
            key: 'planQuantity',
            dataIndex: 'planQuantity',
            defaultValue: '0',
            width: 120,
          },
          {
            title: '辅单位',
            key: 'auUnit',
            dataIndex: 'auUnit',
            dictCode: 'zl_unit',
            type: JVXETypes.select,
            width: 100,
            disabled: true,
          },
          {
            title: '辅数量',
            key: 'auxiliaryQuantity',
            dataIndex: 'auxiliaryQuantity',
            width: 120,
          },
          {
            title: '包装车间',
            key: 'packshopCode',
            type: JVXETypes.slot,
            width: '200px',
            slotName: 'packshopCodeSlot',
            validateRules: [{ required: true, message: '${title}不能为空' }],
            slots: {
              header: () => {
                return [
                  <div class="vxe-cell c--tooltip" style="width: 198px;">
                    <i class="vxe-required-icon"></i>
                    <i class="vxe-edit-icon vxe-icon--edit-outline"></i>
                    <span class="vxe-cell--title">包装车间</span>
                  </div>,
                ]
              },
            },
          },
          {
            title: '配方编码',
            key: 'formulaCode',
            type: JVXETypes.normal,
            width: '160px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            type: JVXETypes.normal,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '包装要求',
            key: 'packReq',
            type: JVXETypes.normal,
            width: '300px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      // 车间计划安排加工
      tslProWorkshopPlanTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            key: 'priority',
            type: JVXETypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            type: JVXETypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '生产计划吨数',
            key: 'auxiliaryQuantity',
            dataIndex: 'auxiliaryQuantity',
            width: 120,
          },
          {
            title: '生产锅',
            key: 'kettleId',
            type: JVXETypes.slot,
            width: '200px',
            slotName: 'kettleIdSlot',
            validateRules: [{ required: true, message: '${title}不能为空' }],
            slots: {
              header: () => {
                return [
                  <div class="vxe-cell c--tooltip" style="width: 198px;">
                    <i class="vxe-required-icon"></i>
                    <i class="vxe-edit-icon vxe-icon--edit-outline"></i>
                    <span class="vxe-cell--title">生产锅</span>
                  </div>,
                ]
              },
            },
          },
          {
            title: '锅数',
            key: 'kettleQuantity',
            type: JVXETypes.inputNumber,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '计划吨数',
            key: 'planQuantity',
            type: JVXETypes.normal,
            width: '100px',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '300px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/pro/tslProWorkshopPlan/add',
        edit: '/pro/tslProWorkshopPlan/edit',
        queryById: '/pro/tslProWorkshopPlan/queryById',
        tslProWorkshopPlanDetail: '/pro/tslProWorkshopPlan/queryWorkshopPlanInfoByMainId',
        kettleList: '/demo/tslMdKettle/list',
        workshopList: '/productionexecutionorganization/erpProductionExecutionOrganization/list',
        packshopList: '/packageorganization/erpPackageOrganization/list',
        FileList: '/pro/tslProWorkshopPlan/queryFileByMainId',
      },
      allKettleList: [],
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    editClosedEvent({ row, column, cellValue }) {
      if (['kettleId', 'kettleQuantity'].includes(column.property)) {
        const kettle = this.allKettleList.find((item) => item.kettleNo === row.kettleId)
        if (kettle && kettle.kettleCapability > 0 && row.kettleQuantity) {
          let newQuantity = (parseFloat(row.kettleQuantity) * parseFloat(kettle.kettleCapability)).toFixed(6)
          this.$set(row, 'planQuantity', newQuantity)
          if (row.tslProScheduleDetail && row.tslProScheduleDetail.length > 0) {
            let details = row.tslProScheduleDetail
            details.forEach((item, index) => {
              if (item.actualNumber) {
                item.formulaQuantity = (item.actualNumber * newQuantity).toFixed(6)
              }
            })
            this.$set(row, 'tslProScheduleDetail', details)
          }
          this.$forceUpdate()
        }
      }
    },
    async loadWorkshopOptions(dataSource) {
      try {
        // 第一步：获取车间选项
        const workshopRes = await getAction(this.url.workshopList, { pageSize: 999, pageNo: 1 })
        if (workshopRes.success) {
          let detailData = workshopRes.result.records || workshopRes.result || []
          if (Array.isArray(detailData)) {
            detailData.forEach((item) => {
              this.workshopOptions.push({
                value: item.departCode,
                text: item.departName,
              })
            })
          }
          // 设置默认值
          if (this.workshopOptions.length > 0 && !this.model.workshopCode) {
            this.model.workshopCode = this.workshopOptions[0].value
          }
        }
        // 第三步：获取包装车间选项
        const packshopRes = await getAction(this.url.packshopList, { pageSize: 999, pageNo: 1 })
        if (packshopRes.success) {
          let detailData = packshopRes.result.records || packshopRes.result || []
          if (Array.isArray(detailData)) {
            detailData.forEach((item) => {
              this.packshopOptions.push({
                value: item.departCode,
                text: item.departName,
              })
            })
          }
        }
        // 第二步：获取生产锅列表
        const kettleRes = await getAction(this.url.kettleList, { pageSize: 999, pageNo: 1 })
        this.allKettleList = kettleRes.result.records || []
        this.kettleOptions = []
        let opt = this.allKettleList.filter((item) => item.workshopNo.indexOf(this.model.workshopCode) > -1)
        this.kettleOptions = opt.map((item) => {
          return { text: item.kettleName, value: item.kettleNo }
        })
        dataSource.forEach((item) => {
          item.kettleOptions = this.kettleOptions
        })
        this.tslProWorkshopPlanTable.dataSource = dataSource
      } catch (error) {
        console.error('加载选项失败:', error)
      }
    },
    workshopChange() {
      this.kettleOptions = []
      let opt = this.allKettleList.filter((item) => item.workshopNo.indexOf(this.model.workshopCode) > -1)
      this.kettleOptions = opt.map((item) => {
        return { text: item.kettleName, value: item.kettleNo }
      })
      const newDataSource = this.tslProWorkshopPlanTable.dataSource.map((row) => ({
        ...row,
        kettleId: '',
        kettleOptions: [...(this.kettleOptions || [])],
      }))
      this.$set(this.tslProWorkshopPlanTable, 'dataSource', newDataSource)
    },
    addBefore() {
      this.tslProWorkshopPlanTable.dataSource = []
    },
    async add(rows, type) {
      this.model.salesType = type
      const merged = rows.reduce((acc, item) => {
        const key = item.formulaNumber ?? 'null'
        let detailSum = 0
        if (Array.isArray(item.tslProScheduleDetail)) {
          detailSum = item.tslProScheduleDetail.reduce((sum, detail) => {
            const auxValue = detail.auxiliaryQuantity ? parseFloat(detail.auxiliaryQuantity) : 0
            return sum + auxValue
          }, 0)
        }
        if (!acc[key]) {
          acc[key] = {
            ...item,
            kettleId: '',
            priority: null,
            auxiliaryQuantity: detailSum, // 保存计算后的总值
            tslProScheduleDetail: [],
            tslProPackageDetail: null,
          }
        } else {
          acc[key].auxiliaryQuantity = (acc[key].auxiliaryQuantity || 0) + detailSum
        }
        if (Array.isArray(item.tslProScheduleDetail)) {
          acc[key].tslProScheduleDetail.push(...item.tslProScheduleDetail)
        }
        return acc
      }, {})
      const newRows = Object.values(merged).map((item, index) => ({
        ...item,
        priority: index + 1,
      }))
      this.loadWorkshopOptions(newRows)
    },
    /**
     * 编辑记录
     * @param {Object} record - 需要编辑的记录对象
     */
    edit(record) {
      this.model = record
      this.tslProWorkshopPlanTable.dataSource = []
      getAction(this.url.tslProWorkshopPlanDetail, { id: record.id }).then((res) => {
        if (res.success) {
          this.loadWorkshopOptions(res.result || [])
        }
      })
      getAction(this.url.FileList, { id: record.id }).then((res) => {
        if (res.success) {
          res.result.forEach((item) => {
            item.fileSizeFormat = $file.calculateFileSize(item.fileSize)
          })
          this.workshopPlanFileTable.dataSource = res.result
        }
      })
    },
    async handleOk() {
      //  校验主表单
      const mainFormValid = await new Promise((resolve) => {
        this.$refs.form.validate((valid) => resolve(valid))
      })
      if (!mainFormValid) return
      const requiredFields = ['kettleId', 'kettleQuantity']
      let hasMissingFields = false
      this.tslProWorkshopPlanTable.dataSource.forEach((row, index) => {
        const planQuantity = Number(row.planQuantity) || 0
        const auxiliaryQuantity = Number(row.auxiliaryQuantity) || 0
        if (planQuantity > auxiliaryQuantity) {
          hasMissingFields = true
          this.$message.error(`第 ${index + 1} 行的计划数量不能大于生产计划数量`)
        }
        requiredFields.forEach((field) => {
          if (!row[field] || row[field] === '') {
            hasMissingFields = true
            this.$message.error(
              `第 ${index + 1} 行的 ${
                this.tslProWorkshopPlanTable.columns.find((col) => col.key === field).title
              } 不能为空`
            )
          }
        })
        if (row.tslProScheduleDetail) {
          row.tslProScheduleDetail.forEach((subRow, subIndex) => {
            if (!subRow.packshopCode || subRow.packshopCode === '') {
              hasMissingFields = true
              this.$message.error(`第 ${index + 1} 行对应的子表第 ${subIndex + 1} 行的包装车间不能为空`)
            }
          })
        }
      })
      if (hasMissingFields) return
      //  调用接口提交（根据实际接口调整）
      this.confirmLoading = true
      this.model.tslProWorkshopPlanInfoList = this.tslProWorkshopPlanTable.dataSource
      if (!this.model.filePath || this.model.filePath.length <= 0) {
        this.model.filePath = []
      }
      this.workshopPlanFileTable.dataSource.forEach((item) => {
        this.model.filePath.push(item)
      })
      if (this.model.filePath.length > 0) {
        this.model.filePath.forEach((item) => {
          if (item.fileSize == null || !item.fileSize) {
            item.fileSize = 0
          }
        })
      }
      try {
        const url = this.model.code ? this.url.edit : this.url.add // 编辑/新增判断
        await postAction(url, this.model)
        this.$message.success('提交成功')
        this.$emit('ok') // 触发提交成功事件，通知模态框
      } catch (error) {
        this.$message.error('提交失败：' + (error.message || '网络异常'))
      } finally {
        this.confirmLoading = false
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    handleFileChange(fileList) {
      if (!fileList || fileList.length <= 0) {
        return
      }
    },
    handlePreviewFile({ row }) {
      FilePreview(row.filePath)
    },
    handleDownloadFile({ row }) {
      return getFileAccessHttpUrl(row.filePath)
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        tslProWorkshopPlanProcessList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
  },
}
</script>

<style scoped></style>
